﻿package 
{
	import flash.net.*;
	import flash.events.*;
	import preferences.*;
	import flash.data.*;
	import flash.utils.getQualifiedClassName;

	public class Intervals
	{
		private static var type:String;
		private var myParent;
		private var myAction;
		private var Params:Object;

		public function Intervals(parent=null, action=null)
		{
			myParent = parent;
			myAction = action;
			Params = new Object();
		}

		public static function get_tasks(url_params:Object)
		{
			Main.Indicator.gotoAndStop(1);
			var settings = new Settings();
			var user_id = settings.get_setting('user_id');
			
			if(!user_id)
			{
				new Errors('No user id has been configured.');
				return;
			}
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE,recieveTasks);
			//var status:String = new String();
			if (url_params.status_id != undefined)
			{
				url_params.status_id = '&statusid=' + url_params.status_id;
			}
			else
			{
				url_params.status_id = '';
			}
			if (url_params.assigneeid != undefined)
			{
				url_params.assigneeid = '&assigneeid=' + url_params.assigneeid;
			}
			else
			{
				url_params.assigneeid = '&assigneeid=' + user_id;
			}
			if (url_params.limit != undefined)
			{
				url_params.limit = '&limit=' + url_params.limit;
			}
			else
			{
				url_params.limit = '&limit=100';
			}
			var cURL = 'https://api.myintervals.com/task/?' + url_params.assigneeid + url_params.status_id + url_params.limit;
			if(user_id)
			{
				api_call('GET', cURL, loader);
			}
		}
		
		public function submit_timer(TaskNumber)
		{
			myParent.intervals_btn.action('intervals_active');
			
			var taskSQL:Tasks = new Tasks();
			Params.task_details = taskSQL.get_task(TaskNumber);

			try
			{
				var task_id = Params.task_details[0]['id'];
			}
			catch(e){
				new Errors("No task_id\n"+e);
				return;
			}

			try
			{
				var project:Projects = new Projects();
				project.get_project(Params.task_details[0]['projectid']);
				Params.project = project;

				if(!project.id || project.id == 0)
				{
					get_project(Params.task_details[0]['projectid']);
				}
				else
				{
					send_submit_xml();
				}
			}
			catch(e){
				new Errors("Project issues...\n"+e);
				return;
			}
		}

		private function send_submit_xml()
		{
			var date:Date = new Date();

			var timeparts = String(myParent.get_time()/1000/60/60).split(".");
			timeparts[1] = timeparts[1].substr(0,3);
			var xmltime = timeparts[0]+'.'+timeparts[1];
			var settings = new Settings();
			var user_id = settings.get_setting('user_id');
			var xml:XML = 
				<time>
					<worktypeid>131298</worktypeid>
					<date>{date.fullYear + '-' + Tools.formatNumber(date.month+1,2) + '-' + Tools.formatNumber(date.date,2)}</date>
					<taskid>{Params.task_details[0]['id']}</taskid>
					<time>{xmltime}</time>
					<billable>{Params.project.billable}</billable>
					<personid>{user_id}</personid>
				</time>;
			try
			{
				//url_params.personid = Main.Settings.user_id;
				var loader:URLLoader = new URLLoader();
				loader.addEventListener(Event.COMPLETE,this.taskSubmitted);
				var cURL = 'https://api.myintervals.com/time/';
			}
			catch(e){new Errors("loader\n"+e);}
			try
			{
				if( user_id)
				{
					api_call('POST', cURL, loader, '<?xml version="1.0" encoding="UTF-8"?>'+xml);
				}
				else
				{
					new Errors('No user id has been configured.');
				}
			}
			catch(e){new Errors("Timer submit fucked up\n"+e);}
		}

		public static function get_projects()
		{
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE,recieveProjects);
			var cURL = 'https://api.myintervals.com/project/?limit=100&active=t';
			api_call('GET', cURL, loader);
		}
		
		public function get_project(projectID)
		{
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE,recieveProject);
			var cURL = 'https://api.myintervals.com/project/'+projectID;
			api_call('GET', cURL, loader);
		}
		
		public static function get_people()
		{
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE,recievePeople);
			var cURL = 'https://api.myintervals.com/person/?limit=100&active=t';
			api_call('GET', cURL, loader);
		}

		public static function get_statuses()
		{
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE,recieveStatuses);
			var cURL = 'https://api.myintervals.com/taskstatus/?limit=50';
			api_call('GET', cURL, loader);
		}

		private static function api_call(method, cURL, loader, url_params=null)
		{
			try
			{
				var req:URLRequest = new URLRequest(cURL);
				var headerRequests:Array = new Array(1);
				req.method = method;
				
				if(method=='POST' && url_params)
				{
					req.contentType = "text/xml";
					req.data = url_params;
				}
	trace(cURL);
				var encoder64:Base64Encoder = new Base64Encoder();
				var settings:Settings = new Settings();
				encoder64.encode(settings.get_setting('api_key') + ":" + 'X');//'8p7vye5tjt8'

				var credentials:String = encoder64.toString();
				headerRequests[0] = new URLRequestHeader("Authorization","Basic " + credentials);
				req.requestHeaders = headerRequests;
				req.authenticate = false;

				loader.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS,onStatus);
				loader.addEventListener(ProgressEvent.PROGRESS,preload);
				loader.addEventListener(IOErrorEvent.IO_ERROR,onError);

				loader.load(req);
			}
			catch(e){ new Errors('API call failed.\n'+e); }
		}
		
		public function get_task(task_id)
		{
			myParent.intervals_btn.action('intervals_active');
			try
			{
				var loader:URLLoader = new URLLoader();
				loader.addEventListener(Event.COMPLETE,recieveTask);
				var cURL = 'https://api.myintervals.com/task/?localid=' + task_id;
				api_call('GET', cURL, loader);
			}
			catch(e){ new Errors('No idea why get_task isnt working.\n'+e); }
		}

		private static function onStatus(event:HTTPStatusEvent):void
		{
			//textbox.output.text += 'Status: ' + event.status.toString() + "\n";
		}

		private static function recieveTasks(event:Event):void
		{
			var xml:XML = new XML(event.target.data);
			var _return:Object = new Object();
			_return._xml = xml;
			_return._type = 'tasks';
			Main.recieve_xml(_return);
		}

		private function recieveTask(event:Event):void
		{
			try
			{
				myParent.intervals_btn.action('intervals_complete');
				var xml:XML = new XML(event.target.data);
				trace(xml);
				if(xml.attribute('status')!='OK' || xml.task.item==undefined)
				{
					throw(new Error());
				}
				var task:Tasks = new Tasks();
				task.set_details(xml.task.item);
				task.insert();
				myParent.set_task(task);
			}
			catch(e)
			{
				new Errors('Something went wrong while getting that task, make sure you got the task number right.');
				myParent.get_task_failed();
			}
		}

		private function taskSubmitted(event:Event):void
		{
			Main.Indicator.gotoAndStop(2);
			var xml:XML = new XML(event.target.data);
			if(xml.attribute('status')!='Created')
			{
				new Errors('Failed to submit time:\n'+xml);
			}
			this.myParent.intervals_btn.action('intervals_complete');
		}

		private static function recievePeople(event:Event):void
		{
			var xml:XML = new XML(event.target.data);
			var _return:Object = new Object();
			_return._xml = xml;
			_return._type = 'people';
			Main.recieve_xml(_return);
		}

		private static function recieveProjects(event:Event):void
		{
			var xml:XML = new XML(event.target.data);
			var _return:Object = new Object();
			_return._xml = xml;
			_return._type = 'projects';
			var projects:Projects = new Projects();
			projects.bulk_insert(xml);
		}

		private function recieveProject(event:Event):void
		{
			var xml:XML = new XML(event.target.data);
			var _return:Object = new Object();
			var project:Projects = new Projects();
			project.set_details(xml);
			project.insert();
			if(this.myAction=='timer_submit')
			{
				Params.project = project;
				send_submit_xml();
			}
		}

		private static function recieveStatuses(event:Event):void
		{
			var xml:XML = new XML(event.target.data);
			var _return:Object = new Object();
			_return._xml = xml;
			_return._type = 'statuses';
			Main.recieve_xml(_return);
		}

		private static function onError(event:IOErrorEvent):void
		{
			switch(event.errorID)
			{
				case 2032:
					new Errors('Connection error... probably no internet connection or something.');
				break;

				default:
					new Errors(event.text);
			}
		}

		private static function preload(e:ProgressEvent)
		{
			//trace(e.bytesLoaded);
		}

	}
}